import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTMLDocument;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;

@WebServlet("/photo")
public class photoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out=resp.getWriter();

        User user=new User();

        String path="/photo";
        String saveDir=req.getServletContext().getRealPath(path);
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //文件上传解析器
        ServletFileUpload upload=new ServletFileUpload(factory);
        //设置所有上传数据的最大值，单位字节long  1M
        //设置单个文件上传的最大值
        //设置编码格式
        try {
            //解析请求，将表单中每个输入项封装成一个FileItem对象
            List<FileItem> items=upload.parseRequest(req);
            if (!items.isEmpty()){
                user=new User();
            }
            Iterator<FileItem> iterator=items.iterator();
            while (iterator.hasNext()){
                FileItem item=iterator.next();
                if (item.isFormField()){
                    if (item.getFieldName().equals("name")){
                        user.setName(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
                    }
                }else {
                    String fileName=item.getName();
                    File file=new File(saveDir+"//"+fileName);
                    item.write(file);
                    user.setPhoto(req.getContextPath()+path+"/"+fileName);
                }
            }
        } catch (Exception e) {
            System.out.println("失败1");
            e.printStackTrace();
        }
        if (user!=null){
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
            String jdbcUser = "root";
            String jdbcPwd = "123456";
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection(url, jdbcUser, jdbcPwd);
                String sql="insert into test(name,photo) values(?,?)";
                PreparedStatement pstmt=conn.prepareStatement(sql);
                pstmt.setString(1,user.getName());
                pstmt.setString(2,user.getPhoto());
                int rows=0;
                rows=pstmt.executeUpdate();
                if (rows==1){
                    System.out.println("成功");
                }else{
                    System.out.println("失败2");
                }
            }catch (Exception e){
                System.out.println("失败3");
            }
        }else {
            System.out.println("失败4");
        }
        out.println("<img src="+user.getPhoto()+" width=300px height=200px/>");
    }
}
